﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace FlanProjectData.Sprites
{
    public class AnimatingSprite
    {
        public Animation Animation { get; set; }
        public float CurrentTime { get; set; }
        public int FrameIndex { get; set; }

        public bool IsAnimationComplete
        {
            get
            {
                return Animation == null || (!Animation.IsLooping && (FrameIndex == Animation.FrameList.Count - 1));
            }
        }

        public void Reset()
        {
            CurrentTime = 0;
            FrameIndex = 0;
        }

        public void PlayAnimation(Animation animation)
        {
            if (Animation != animation)
            {
                Animation = animation;
                Reset();
            }
        }

        public void Draw(SpriteBatch spriteBatch, SpriteEffects spriteEffect, Vector2 position, GameTime gameTime, Color? color = null)
        {
            if (Animation == null)
                throw new NullReferenceException("No animation loaded.");

            try
            {
                CurrentTime += (float)gameTime.ElapsedGameTime.TotalSeconds;

                while (CurrentTime > Animation.FramePerSecond)
                {
                    CurrentTime -= Animation.FramePerSecond;
                    FrameIndex = Animation.IsLooping ? (FrameIndex + 1) % Animation.FrameList.Count
                        : Math.Min(FrameIndex + 1, Animation.FrameList.Count - 1);
                }

                // Draw from bottom-left corner
                spriteBatch.Draw(Animation.SpriteTexture, position, Animation.FrameList[FrameIndex], color.HasValue ? color.Value : Color.White, 0.0f, new Vector2(0, Animation.FrameList[FrameIndex].Height), 1.0f, spriteEffect, 0);
            }
            catch (Exception e)
            {
                Console.WriteLine("Stack trace : " + e.StackTrace);
            }
        }
    }
}
